<template>

  <div>
    <!-- 添加或修改对话框 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="title"
      :visible.sync="dialogFormVisible"
      :before-close="beforeClose"
      fullscreen
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-row>
            <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
              <el-input v-model="form.title" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
            <el-form-item label="简介" :label-width="formLabelWidth">
              <el-input v-model="form.summary" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
        </el-row>

        <el-row>
            <el-form-item label="标题图" :label-width="formLabelWidth">
              <div class="imgBody" v-if="form.photoList">
                <i
                  class="el-icon-error inputClass"
                  v-show="icon"
                  @click="deletePhoto()"
                  @mouseover="icon = true"
                ></i>
                <img
                  @mouseover="icon = true"
                  @mouseout="icon = false"
                  v-bind:src="form.photoList[0]"
                  style="display:inline; width: 195px;height: 105px;"
                >
              </div>

              <div v-else class="uploadImgBody" @click="checkPhoto">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </div>

            </el-form-item>
        </el-row>

        <el-row>
          
          <el-form-item label="分类" :label-width="formLabelWidth" prop="rankUid">
              <el-select
                @input="contentChange"
                v-model="form.rankUid"
                size="small"
                placeholder="请选择"
                style="width:150px"
              >
                <el-option
                  v-for="item in rankData"
                  :key="item.uid"
                  :label="item.rankName"
                  :value="item.uid"
                ></el-option>
              </el-select>
            </el-form-item>
          
        </el-row>
        
        <!-- <el-row>
          <el-col :lg="5" :sm="8" :xs="8">
            
            <el-form-item label="标签" :label-width="formLabelWidth" prop="tagUid">
              <el-select
                @input="contentChange"
                v-model="tagValue"
                multiple
                :multiple-limit="3"
                size="small"
                placeholder="请选择"
                style="width:250px"
                filterable
              >
                <el-option
                  v-for="item in tagData"
                  :key="item.uid"
                  :label="item.tagName"
                  :value="item.uid"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row> -->

        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="城市" :label-width="formLabelWidth" prop="city">
              <el-cascader
                    size="large"
                    clearable
                    ref="cascader"
                    :options="options"
                    v-model="form.selectedCity"
                    @change="handleChange"
                    class="w250"
                >
                </el-cascader>
            </el-form-item>
          </el-col>

          <el-col :lg="12" :sm="16" :xs="16">
            <el-form-item label="详细地址" label-width="100px" prop="address">
              <el-input v-model="form.address" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="活动时间" :label-width="formLabelWidth" prop="timeRange">
              <el-date-picker
                v-model="form.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>


        </el-row>
        
        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="报名截止时间" :label-width="formLabelWidth" prop="applyEndTime">
              <el-date-picker
                v-model="form.applyEndTime"
                type="datetime"
                placeholder="选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        
        <el-row>
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="报名费（元）" :label-width="formLabelWidth" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1"></el-input-number>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          
          <el-form-item label="支付方式" :label-width="formLabelWidth" prop="payMethod">
              <el-select
                @input="contentChange"
                v-model="form.payMethod"
                size="small"
                placeholder="请选择"
                style="width:150px"
              >
                <el-option
                  v-for="item in payMethodList"
                  :key="item.payMethod"
                  :label="item.payMethodName"
                  :value="item.payMethod"
                ></el-option>
              </el-select>
            </el-form-item>
          
        </el-row>
        
        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="人数上限" :label-width="formLabelWidth" prop="allowPeopleNum">
              <el-input-number v-model="form.allowPeopleNum" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          
        </el-row>

        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
              <el-input v-model="form.remark" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>  
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="本人微信" :label-width="formLabelWidth" prop="weChat">
              <el-input v-model="form.weChat" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row> 
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="本人手机" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="form.phone" auto-complete="off" @input="contentChange"></el-input>
            </el-form-item>
          </el-col>

        </el-row>


        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="需要领队人数" :label-width="formLabelWidth" prop="allowLeaderNum">
              <el-input-number v-model="form.allowLeaderNum" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          
        </el-row>

        <el-row>
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="领队佣金（元）" :label-width="formLabelWidth" prop="leaderSalary">
              <el-input-number v-model="form.leaderSalary" :min="0" :precision="2" :step="0.1"></el-input-number>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="领队截止时间" :label-width="formLabelWidth" prop="leaderApplyEndTime">
              <el-date-picker
                v-model="form.leaderApplyEndTime"
                type="datetime"
                placeholder="领队报名截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
        
        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="领队条件" :label-width="formLabelWidth" prop="leaderCondition">
              <el-input v-model="form.leaderCondition" auto-complete="off" @input="contentChange" placeholder="领队应具备的条件"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="领队任务" :label-width="formLabelWidth" prop="leaderTask">
              <el-input v-model="form.leaderTask" auto-complete="off" @input="contentChange" placeholder="领队具体的工作内容"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          
          <el-col :lg="5" :sm="8" :xs="8">
            <el-form-item label="领队备注" :label-width="formLabelWidth" prop="leaderRemark">
              <el-input v-model="form.leaderRemark" auto-complete="off" @input="contentChange" placeholder="请输入对领队的补充内容"></el-input>
            </el-form-item>
          </el-col>

        </el-row>



        <el-form-item label="内容" :label-width="formLabelWidth" prop="content">
<!--          <MarkdownEditor ref="editor" v-if="editorModel == '1'" @contentChange="contentChange" :content="form.content"  :height="560"></MarkdownEditor>-->
          <mavon ref="editor" v-if="editorModel === '1'" :context="form.content" @contentChange= "contentChange" :height="560"></mavon>
          <CKEditor ref="editor" v-else :content="form.content" @contentChange="contentChange" :height="465"></CKEditor>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="info" @click="submitDraft">保存草稿</el-button>
        <el-button type="primary" @click="submitForm">提交审核</el-button>
      </span>

    </el-dialog>

    <!--头像裁剪-->
    <avatar-cropper
      v-show="imagecropperShow"
      :key="imagecropperKey"
      :width="400"
      :height="200"
      :url="url"
      lang-type="zh"
      :noCircle="true"
      :noSquare="true"
      @close="close"
      @crop-upload-success="cropSuccess"
    />

    <PhotoGallery v-if="showPhotoGallery" @uploadCallback="uploadCallback" @close="photoGalleryClose" @chooseCallback="chooseCallback"></PhotoGallery>

  </div>

</template>

<script>
import CKEditor from "../CKEditor";
import MarkdownEditor from "../MarkdownEditor";
import AvatarCropper from '@/components/AvatarCropper'
import {getListByDictTypeList} from "@/api/sysDictData"
import {addRankMember, editRankMember, getRankList, getPayMethodPageList} from "@/api/createBlog"
import {formatData} from "@/utils/webUtils";
import Mavon from "../Mavon";
import PhotoGallery from "../PhotoGallery";
import { provinceAndCityData, codeToText } from 'element-china-area-data'

export default {
  props: ["visible", "isEdit", "formData", "editorModel"],
  created() {
    this.rankList()
    this.getPayMethodList()
    //this.tagList()
    window.addEventListener('beforeunload', e => this.beforeUnload(e))
  },
  components: {
    CKEditor,
    MarkdownEditor,
    AvatarCropper,
    Mavon,
    PhotoGallery,
  },
  watch: {
    visible: function() {
      this.dialogFormVisible = this.visible;
    },
  },
  mounted() {
    this.getDictList()
    console.log("编辑器模式", this.editorModel)
  },
  data() {
    return {
      form: {
        uid: null,
        summary: null,
        title: null,
        content: null,
        fileUid: null,
        //tagUid: null,
        //tagList: null,
        rankUid: null,
				payMethod: 0,
        isPublish: null,
        province: null,
        provinceCode: null,
        city: null,
        cityCode: null,
        district: null,
        districtCode: null,
        longitude: null,
        latitude: null,
        address: null,
        startTime: null,
        endTime: null,
        applyEndTime: null,
        price: "",
        allowPeopleNum: 0,
        remark: null,
        weChat: null,
        phone: null,
      
        selectedCity: [],
        timeRange: [],
        
        leaderSalary: 0,
        leaderCondition: null,
        leaderTask: null,
        leaderRemark: null,
        leaderApplyEndTime: ''
      },
      options: provinceAndCityData,
      
      icon: false,
      isSubmitOp: false,
      formLabelWidth: "120px",
      lineLabelWidth: "120px", //一行的间隔数
      maxLineLabelWidth: "100px",
      memberOriginalDictList: [], //存储区域字典
      memberPublishDictList:[],//是否字典
      openDictList: [], // 是否启动字典
      memberOriginalDefault: null, //博客原创默认值
      memberPublishDefault: null, //博客发布默认值
      openDefault: null, // 是否开启评论默认值
      rankData: [],
      payMethodList: [],
      //tagData: [], //标签数据
      //tagValue: [], //保存选中标签id(编辑时)
      dialogFormVisible: this.visible,
      title: "创建活动",
      imagecropperShow: false,
      imagecropperKey: 0,
      url: process.env.FILE_API + "/file/cropperPicture",
      isChange: false, // 表单内容是否改变
      changeCount: 0, // 改变计数器
      showPhotoGallery: false,
      rules: {
        title: [
          {required: true, message: '标题不能为空', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在2到50个字符'},
        ],
        // tagUid: [
        //   {required: true, message: '标签不能为空', trigger: 'blur'}
        // ],
        rankUid: [
          {required: true, message: '分类不能为空', trigger: 'blur'}
        ],
        payMethod: [
          {required: true, message: '支付方式不能为空', trigger: 'blur'}
        ],
        city: [{ required: true, message: "城市不能为空", trigger: "blur" }],
        address: [
          { 
            required: true, message: "详细地址不能为空", trigger: "blur" 
          }
        ],
        timeRange: [
          {
            required: true,
            message: "活动时间不能为空",
            trigger: "blur"
          }
        ],
        applyEndTime: [
          {
            required: true,
            message: "报名截止日期不能为空",
            trigger: "blur"
          }
        ],
        price: [
          { required: true, message: "报名费不能为空", trigger: "blur" }
        ],
        allowPeopleNum: [
          { required: true, message: "报名人数上限不能为空", trigger: "blur" }
        ],
        weChat: [
          { 
            required: true, message: "本人微信不能为空", trigger: "blur" 
          }
        ],
        phone: [
          {required: false, pattern: /0?(13|14|15|17|18)[0-9]{9}/, message: '请输入正确的手机号码'}
        ],
        isPublish: [
          {required: true, message: '发布字段不能为空', trigger: 'blur'},
          {pattern: /^[0-9]\d*$/, message: '发布字段只能为自然数'},
        ],
        content: [
          {required: true, message: '内容不能为空', trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    /**
     * 字典查询
     */
    getDictList: function () {
      // 判断是否处于编辑模式
      let that = this
      let dictTypeList =  [ 'sys_original_status', 'sys_normal_disable','sys_publish_status']
      getListByDictTypeList(dictTypeList).then(response => {
        if (response.code == this.$ECode.SUCCESS) {
          let dictMap = response.data;
          console.log(dictMap.sys_publish_status.list)
          this.memberOriginalDictList = dictMap.sys_original_status.list
          this.memberPublishDictList = dictMap.sys_publish_status.list
          this.openDictList = dictMap.sys_normal_disable.list

          if(dictMap.sys_original_status.defaultValue) {
            this.memberOriginalDefault = dictMap.sys_original_status.defaultValue;
          }
          if(dictMap.sys_publish_status.defaultValue) {
            this.memberPublishDefault = dictMap.sys_publish_status.defaultValue;
          }
          if(dictMap.sys_normal_disable.defaultValue) {
            this.openDefault = dictMap.sys_normal_disable.defaultValue;
          }

          if(this.isEdit) {
            this.form = this.formData
            setTimeout(()=>{
              that.$refs.editor.setData(that.form.content); //设置富文本内容
            },100)
            // that.tagValue = [];
            // console.log(this.form.tagList,"this.form.tagList");
            // if (this.form.tagList) {
            //   let json = this.form.tagList;
            //   for (let i = 0, l = json.length; i < l; i++) {
            //     if (json[i] != null) {
            //       that.tagValue.push(json[i]["uid"]);
            //     }
            //   }
            // }
            that.form.timeRange = []
            if(this.form.startTime){
              that.form.timeRange.push(this.form.startTime);
            }
            if(this.form.endTime){
              that.form.timeRange.push(this.form.endTime);
            }
            this.form.selectedCity = []
            if(this.form.provinceCode){
              that.form.selectedCity.push(this.form.provinceCode);
            }
            if(this.form.cityCode){
              that.form.selectedCity.push(this.form.cityCode);
            }

          } else {
            let tempForm = null;
            console.log("判断缓存中是否有内容", window.localStorage)
            if(window.localStorage && window.localStorage.getItem("form")) {
              tempForm = JSON.parse(window.localStorage.getItem("form"));
            }
            this.$refs.editor.initData(); //设置富文本内容
            if (tempForm != null && tempForm.title != null && tempForm.title != "") {
              this.$confirm("还有上次未完成的文章编辑，是否继续编辑?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              })
                .then(() => {
                  that.dialogFormVisible = true;
                  //that.tagValue = [];
                  that.form = tempForm;
                  // let tagValue = that.form.tagUid.split(",");
                  // for (let a = 0; a < tagValue.length; a++) {
                  //   if (tagValue[a] != null && tagValue[a] != "") {
                  //     that.tagValue.push(tagValue[a]);
                  //   }
                  // }
                  that.$nextTick(() => {
                    //DOM现在更新了
                    that.$refs.editor.setData(that.form.content); //设置富文本内容
                  });
                  if(that.form.uid) {
                    that.title = "编辑博客";
                    that.isEditForm = true;
                  } else {
                    that.title = "新增博客";
                    that.isEditForm = false;
                  }
                })
                .catch(() => {
                  window.localStorage.clear()
                  that.dialogFormVisible = true;
                  that.form = that.getFormObject();
                  that.$nextTick(() => {
                    //DOM现在更新了
                    that.$refs.editor.initData(); //设置富文本内容
                  });
                  //that.tagValue = [];
                  that.isEditForm = false;
                  that.title = "新增博客";
                });
            } else {
              that.dialogFormVisible = true;
              that.form = that.getFormObject();
              that.$nextTick(() => {
                //初始化内容
                that.$refs.editor.initData();
              });
              //that.tagValue = [];
              that.isEditForm = false;
            }
          }
        }
      });
    },
    getFormObject: function() {
      let formObject = {
        uid: null,
        title: null,
        summary: null,
        content: null,
        //tagUid: null,
        rankUid: null,
				payMethod: 0,
        fileUid: null,
        isPublish: this.memberPublishDefault,
        province: null,
        provinceCode: null,
        city: null,
        cityCode: null,
        district: null,
        districtCode: null,
        longitude: null,
        latitude: null,
        address: null,
        startTime: null,
        endTime: null,
        applyEndTime: null,
        price: "",
        allowPeopleNum: 0,
        remark: null,
        weChat: null,
        phone: null,
        selectedCity: [],
        timeRange: [],
        
        leaderSalary: 0,
        leaderCondition: null,
        leaderTask: null,
        leaderRemark: null,
        leaderApplyEndTime: ''

      };
      return formObject;
    },
    photoGalleryClose() {
      this.showPhotoGallery = false
    },
    uploadCallback() {
      this.showPhotoGallery = false
      this.imagecropperShow = true
    },
    beforeUnload: function (e) {
      console.log("刷新页面的回调", this.isSubmitOp)
      if (this.isSubmitOp) {
        return
      }
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = '关闭提示';
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return '关闭提示';
    },
    submitDraft: function () {
      this.form.isPublish = "0"
      this.submit();
    },
    submitForm: function () {
      this.form.isPublish = "1"
      this.submit();
    },
    submit: function() {
      let url = window.location.href
      // if(this.tagValue.length <= 0) {
      //   this.$commonUtil.message.error("标签不能为空!")
      //   return;
      // }
      this.isSubmitOp = true
      this.form.content = this.$refs.editor.getData();
      //this.form.tagUid = this.tagValue.join(",");
      this.form.startTime = this.form.timeRange[0],
      this.form.endTime = this.form.timeRange[1],
      this.$refs.form.validate((valid) => {
        if(!valid) {
          console.log("校验出错")
        } else {
          if (this.isEdit) {
            editRankMember(this.form).then(response => {
              if (response.code == this.$ECode.SUCCESS) {
                this.$commonUtil.message.success(response.message)
                // 清空缓存
                window.localStorage.clear()
                // this.$emit("beforeClose", "");
                setTimeout(()=> {
                  // 跳转到我的文章
                  window.location.href = this.$commonUtil.urlAppendParams(url, "action", "MyArticle")
                }, 500)
              } else {
                this.$commonUtil.message.error(response.message)
              }
            });

          } else {
            addRankMember(this.form).then(response => {
              if (response.code == this.$ECode.SUCCESS) {
                this.$commonUtil.message.success(response.message)
                // 清空缓存
                window.localStorage.clear()
                setTimeout(()=> {
                  // 跳转到我的文章
                  window.location.href = this.$commonUtil.urlAppendParams(url, "action", "MyArticle")
                }, 500)
              } else {
                this.$commonUtil.message.error(response.message)
              }
            });
          }
        }
      })
    },
    rankList: function() {
      let rankParams = {};
      rankParams.pageSize = 100;
      rankParams.currentPage = 1;
      getRankList(rankParams).then(response => {
        console.log(response,"response")
        if(response.code == this.$ECode.SUCCESS) {
          this.rankData = response.data;
          console.log(this.rankData)
          this.rankOptions = response.data;
        }
      });
    },
    getPayMethodList() {
      let params = {};
      getPayMethodPageList(params).then(response => {
        console.log("获取支付方式", response)
        if (response.code == this.$ECode.SUCCESS) {
          this.payMethodList = response.data;
        }
      });
    },
    // tagList: function() {
    //   let tagParams = {};
    //   tagParams.pageSize = 100;
    //   tagParams.currentPage = 1;
    //   getMemberTagList(tagParams).then(response => {
    //     this.tagData = response.data.records;
    //     this.tagOptions = response.data.records;
    //   });
    // },
    checkPhoto: function () {
      // this.imagecropperShow = true
      this.showPhotoGallery = true
    },
    // 内容改变，触发监听
    contentChange: function() {
      console.log("内容改变")
      let that = this;
      if(that.changeCount > 1) {
        that.isChange = true;
        that.form.content = that.$refs.editor.getData(); //获取文本中的内容
        //that.form.tagUid = that.tagValue.join(",");
        // 将内容设置到 WebStorage中
        console.log("备份的内容", that.form)
        // 提交的时候，不允许备份了
        if(!this.isSubmitOp) {
          window.localStorage.setItem("form", JSON.stringify(that.form))
        }
      }
      this.changeCount = this.changeCount + 1;
    },
    // 关闭时的回调
    beforeClose(done) {
      this.$confirm("是否关闭博客编辑窗口", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(() => {
        this.isChange = false;
        this.changeCount = 0
        //取消时，开始状态
        this.$emit("beforeClose", "");
        done();
      })
      .catch(() => {
        // this.$commonUtil.message.info("已取消")
      });
    },
    cancel: function () {
      this.$emit("beforeClose", "");
    },
    // 头像裁剪关闭回调
    close() {
      this.imagecropperShow = false
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      console.log("裁剪后的数据", resData)
      let array = new Array()
      array.push(resData.url)
      this.form.photoList = array
      this.form.fileUid = resData.uid
      this.contentChange()
    },
    chooseCallback(file) {
      console.log("回调", file)
      let array = new Array()
      array.push(file.pictureUrl)
      this.form.photoList = array
      this.form.fileUid = file.uid
      this.contentChange()
      this.showPhotoGallery = false
    },
    deletePhoto: function() {
      console.log("删除")
      let bakFrom = this.form
      this.form = {}
      bakFrom.photoList = null;
      bakFrom.fileUid = "";
      this.form = bakFrom
    },

    // 地图
    handleChange(e) {
      console.log(e,'省市区');
      this.form.provinceCode = this.form.selectedCity[0];
      this.form.province = codeToText[this.form.provinceCode]
      this.form.cityCode = this.form.selectedCity[1];
      this.form.city = codeToText[this.form.cityCode]
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  margin: 0, 0, 0, 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width:  195px;
  height: 105px;
  line-height: 105px;
  text-align: center;
}
.imgBody {
  width:  195px;
  height: 105px;
  border: solid 2px #ffffff;
  float: left;
  position: relative;
}
.uploadImgBody {
  margin-left: 5px;
  width:  195px;
  height: 105px;
  border: dashed 1px #c0c0c0;
  float: left;
  position: relative;
}
.uploadImgBody :hover {
  border: dashed 1px #00ccff;
}
.inputClass {
  position: absolute;
}
</style>
